import { AppDataSource } from "@/config/database";
import { Services } from "@/entities/basis/services.entity";
import { ErrorHandler } from "@/middlewares/error.middleware";
import { Context } from "koa";

export interface IQuery {
    /** 页码，从1开始，默认为1 */
    page?: number;
    /** 每页数量，默认为10，最大100 */
    pageSize?: number;
    /** 搜索关键词，支持服务名称、编码、描述的模糊搜索 */
    keyword?: string;
    /** 服务分类筛选 */
    category?: string;
    /** 服务状态筛选 */
    status?: string;
}

/** 获取服务列表 */
export async function getServiceList(ctx: Context) {
    const query = ctx.request.query as IQuery;
    
    const { page = 1, pageSize = 10, keyword, category, status } = query;

    // 验证分页参数
    validatePaginationParams(page, pageSize);

    // 获取服务列表
    const result = await getServicesWithPagination(page, pageSize, keyword, category, status);

    ctx.status = 200;
    ctx.body = result;
}

/** 验证分页参数 */
const validatePaginationParams = (page: number, pageSize: number) => {
    if (page < 1) {
        throw new ErrorHandler('页码必须大于0', 400);
    }
    if (pageSize < 1 || pageSize > 100) {
        throw new ErrorHandler('每页数量必须在1-100之间', 400);
    }
}

/** 获取分页服务列表 */
const getServicesWithPagination = async (
    page: number, 
    pageSize: number, 
    keyword?: string, 
    category?: string, 
    status?: string
) => {
    const serviceRepository = AppDataSource.getRepository(Services);
    
    // 构建查询条件
    const whereConditions: any = {};
    
    if (category) {
        whereConditions.category = category;
    }
    
    if (status) {
        whereConditions.status = status;
    }

    // 构建查询
    const queryBuilder = serviceRepository.createQueryBuilder('service')
        .where(whereConditions);
        

    // 添加关键词搜索
    if (keyword) {
        queryBuilder.andWhere(
            '(service.name LIKE :keyword OR service.code LIKE :keyword OR service.description LIKE :keyword)',
            { keyword: `%${keyword}%` }
        );
    }

    // 添加排序
    queryBuilder.orderBy('service.updatedAt', 'DESC');

    // 获取总数
    const total = await queryBuilder.getCount();

    // 添加分页
    const skip = (page - 1) * pageSize;
    queryBuilder.skip(skip).take(pageSize);

    // 获取数据
    const services = await queryBuilder.getMany();

    return {
        items: services,
        pagination: {
            page,
            pageSize,
            total,
        }
    };
} 